import {
  ArgumentsHost,
  BadRequestException,
  Catch,
  ExceptionFilter,
  HttpException,
  NotFoundException,
  UnauthorizedException,
} from '@nestjs/common';
import { Response } from 'express';
import { BusinessException } from '../../types/exception/business.exception';
import { ApiReturnType } from '../../types/interface/api.interface';
import { HTTP_CODE } from '../../types/enum/http-code.enum';
import { ERR_MSG } from '../../types/errcode';
@Catch()
export class CustomExceptionFilter implements ExceptionFilter {
  catch(exception: Error, host: ArgumentsHost) {
    let body: ApiReturnType<string | object> = {
      success: false,
      data: {},
      code: '',
      msg: { desc: exception.name, detail: exception.message },
      timestamp: Date.now(),
    };
    // 获取 http 数据
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    // const request = ctx.getRequest<Request>();
    console.log(exception,'exception');
    // 错误分类进行处理
    if (exception instanceof UnauthorizedException) {
      // jwt 错误
      const errObj = ERR_MSG.AUTH_JWT_ERROR;
      body = {
        success: false,
        code: errObj.code,
        data: {},
        msg: { desc: errObj.msg },
        timestamp: Date.now(),
      };

      return response.status(HTTP_CODE.JWT_ERROR).json(body);
    } else if (exception instanceof BadRequestException) {
      // 请求参数 dto 未通过
      const errObj = ERR_MSG.PARAMS_NOT_MATCH;
      body = {
        success: false,
        code: errObj.code,
        data: {},
        msg: { desc: errObj.msg, detail: exception.getResponse() },
        timestamp: Date.now(),
      };
      return response.status(HTTP_CODE.DTO_NOT_MATCH).json(body);
    } else if (exception instanceof NotFoundException) {
      // 路由请求不存在
      const errObj = ERR_MSG.ROUTE_NOT_FOUND;
      body = {
        success: false,
        code: errObj.code,
        data: {},
        msg: { desc: errObj.msg, detail: exception.getResponse() },
        timestamp: Date.now(),
      };
      return response.status(HTTP_CODE.ROUTE_METHOD_WRONG).json(body);
    } else if (exception instanceof BusinessException) {
      // 业务错误
      body = {
        success: false,
        code: exception.getCode,
        data: {},
        msg: { desc: exception.getMsg },
        timestamp: Date.now(),
      };

      // 业务错误不需要修改 http code,默认为 200
      return response.json(body);
    } else if (exception instanceof HttpException) {
      // http错误
      return response.status(exception.getStatus()).json(body);
    } else if (exception instanceof Error) {
      // 通用错误
      return response.status(HTTP_CODE.SERVER_ERROR).json(body);
    }
  }
}
